package com.mpgame.caller;

import java.util.List;
import java.util.concurrent.TimeUnit;

import com.mpgame.common.connection.GrpcConnectionPool;
import com.mpgame.common.handler.GrpcCallHandler;
import com.mpgame.common.proto.*;
import com.mpgame.connection.ChannelRegistry;
import com.mpgame.database.redis.model.UserTokenInfo;
import com.mpgame.common.utils.Log;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.Channel;

public class ChatServiceCaller {
    private final GrpcConnectionPool pool;
    public ChatServiceCaller(GrpcConnectionPool pool){
        this.pool = pool;
    }
    public boolean handleChat(ChannelHandlerContext ctx, GamePacket pkt){
        return GrpcCallHandler.invoke(
            ctx, pkt, pool, CmdId.CHAT_RSP,
            // 解析请求
            data -> {
                try {
                    ChatReq req = ChatReq.parseFrom(data);

                    UserTokenInfo userTokenInfo = ChannelRegistry.getUseTokenInfoFromChannel(ctx.channel());
                
                    req = ChatReq.newBuilder(req)
                        .setSenderName(userTokenInfo.getNickname())
                        .build();

                    return req;
                } catch (Exception e) {
                    return null;
                }
            },
            // 构造 stub
            cli -> ChatServerServiceGrpc.newBlockingStub(cli.getChannel())
                    .withDeadlineAfter(10, TimeUnit.SECONDS),
            // 发起 rpc
            (stub, req) -> stub.sendMsg(req),
            // 提取错误信息
            ChatRspBroadcast::getErrMsg,
            // 返回给客户端
            rsp -> {
                GamePacket rpkt = GamePacket.newBuilder()
                    .setCmd(CmdId.CHAT_RSP)
                    .setData(rsp.getRsp().toByteString())
                    .build();
                forwardToTargetplayers(rsp.getTargetPlayersList(), rpkt);
                return rsp;
            });
    }


    private void forwardToTargetplayers(List<Integer> targetPlayerIds, GamePacket pkt){
        if(targetPlayerIds == null || targetPlayerIds.isEmpty()){
            Log.warn("转发聊天消息给目标玩家，但目标玩家列表为空");
            return;
        }

        int successCount = 0, offlineCount = 0;

        if(targetPlayerIds.get(0) != -1){
            for(Integer playerId : targetPlayerIds){
                String playerIdStr = String.valueOf(playerId);
                Channel ch = ChannelRegistry.getPlayerConnection(playerIdStr);
    
                if(ch != null && ch.isActive()){
                    ch.writeAndFlush(pkt);
                    successCount++;
                    Log.info("转发聊天消息给目标玩家：" + playerIdStr);
                }
                else{
                    offlineCount++;
                    Log.warn("转发聊天消息给目标玩家，但目标玩家连接不存在：" + playerIdStr);
                }
            }
        }// 转发给所有玩家
        else{
            Log.info("消息转发给所有玩家");
            for(Channel ch : ChannelRegistry.getPlayerConnections()){
                if(ch != null && ch.isActive()){
                    ch.writeAndFlush(pkt);
                    successCount++;
                }
                else{
                    offlineCount++;
                }
            }
        }
        Log.info("消息转发完成 - 成功：" + successCount + "，离线：" + offlineCount);
    }
}
